package zhqs;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 绿米设备局域网开发demo程序（利用组播技术实现）
 *
 */
public class Muiltcast {

    static class MulticastClient {

        private MulticastSocket socket;
        private InetAddress group;
        private int port;

        public MulticastClient(InetAddress group, int port) throws IOException {

            this.group = group;
            this.port = port;
            socket = new MulticastSocket(port);
            socket.joinGroup(group);
            final byte[] buf = new byte[1024];
            new Thread(new Runnable() {
                @Override
                public void run() {

                    // TODO 生产环境中，此处需要增加一段守护线程，如果超时，则跳出并且continue

                    while (true) {
                        try {
                            DatagramPacket packet = new DatagramPacket(buf, buf.length);
                            socket.receive(packet);
                            String msg = new String(packet.getData()).substring(0, packet.getLength());  // 截取缓冲区中的新数据

                            String now = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format( new Date() );
                            System.out.println( now + " 返回的数据：  " + msg);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();

        }

        public void send(String msg) {
            byte[] bytes = msg.getBytes();
            try {
                socket.leaveGroup(group);//发送的人不接收组播消息
                msg = "发送数据：" + msg;
                System.out.println(msg);
                socket.send(new DatagramPacket(bytes, bytes.length, group, port));
                socket.joinGroup(group);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 绿米设备局域网开发demo程序
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {


//        空调伴侣
//        智能插座
//        墙壁插座
//        墙壁开关（零火单键）
//        墙壁开关（零火双键）
//        墙壁开关（单火单键）
//        墙壁开关（单火双键）
//        窗帘电机
//        空调温控器
//        门窗传感器
//        人体传感器
//        温湿度传感器
//        水浸传感器



        MulticastClient multicastClient;

        // 获取网关列表
        multicastClient = new MulticastClient(InetAddress.getByName("224.0.0.50"), 4321);
        multicastClient.send("{\"cmd\":\"whois\"}");

        // 获取上报 获取网关中的子设备
        multicastClient = new MulticastClient(InetAddress.getByName("224.0.0.50"), 9898);
        multicastClient.send("{\"cmd\":\"discovery\"}");

        // 唤醒广播监听（生产环境中，可以按照实际业务的需求进行调整时长）
        while (true) {
            Thread.sleep(1000*20);
            multicastClient.send("{\"cmd\":\"discovery\"}");
        }

        // 读设备状态
//        multicastClient.send("{\"cmd\":\"read\",\"sid\":\"158d00047f7d60\"}");


        // 写设备状态-空调示例
//        String strAES = LvmiTokenEncry.encry("kFabk1qIoGNtyh67","262245009a90307a");
//        String strStatus = "on";
//        multicastClient.send("{\"cmd\":\"write\",\"model\":\"acpartner.v3\",\"sid\":\"5ce50cb65788\",\"key\":\"" + strAES + "\",\"params\":[{\"on_off_cfg\":\"" + strStatus + "\"}]}");

        // 写设备状态-墙壁插座示例
//        String strAES = LvmiTokenEncry.encry("eHMJkmhHGtWsXSCz","262245009a90307a");
//        String strStatus = "off";
//        multicastClient.send("{\"cmd\":\"write\",\"model\":\"ctrl_86plug.aq1\",\"sid\":\"158d00047f7d60\",\"key\":\"" + strAES + "\",\"params\":[{\"channel_0\":\"" + strStatus + "\"}]}");


        // 写设备状态-窗帘电机示例
//        String strAES = LvmiTokenEncry.encry("SnM0QLl5o1vq5IAg","262245009a90307a");
//        String strStatus = "open";  //open/close/stop/auto
//        multicastClient.send("{\"cmd\":\"write\",\"model\":\"ctrl_86plug.aq1\",\"sid\":\"158d00040b016d\",\"key\":\"" + strAES + "\",\"params\":[{\"curtain_status\":\"" + strStatus + "\"}]}");

    }
}